/**
 * Created by zhangsong on 2019-01-18.
 */

module.exports = class Cache {

  constructor({ func, limit = 100 }) {
    if (typeof func !== 'function') {
      throw new Error('func is not function');
    }
    this.running = false;
    this.done = false;
    this.arr = [];
    this.works = [];
    this.limit = limit;
    this.callback = func;
  }

  set(obj) {
    this.arr.push(obj);
    if (this.arr.length >= this.limit) {
      const old = this.arr;
      this.arr = [];
      this.exec(old);
    }
  }

  exec(obj) {
    if (obj) {
      this.works.push(obj);
    }
    if (!this.running) { // 正有任务在运行,缓存数据
      const data = this.works.shift();
      if (data) { // 如果有数据,执行回调
        this.running = true;
        this.done = false;
        this.callback(data).then(() => {
          this.running = false;
          return this.exec();
        }).catch((e) => {
          console.error(e);
        });
      } else {
        console.log('任务完成');
        this.done = true;
        this.running = false;
      }
    }
  }

  hasDone(callback) {
    setTimeout(() => {
      if (this.done) {
        callback();
      } else {
        this.hasDone(callback);
      }
    }, 3000);
  }

  isDone() {
    return new Promise((resolve, reject) => {
      this.hasDone(resolve);
    });
  }

};
